//
//  TWGridLayout.m
//  自定义布局
//
//  Created by 耐克了解了 on 17/4/17.
//  Copyright © 2017年 耐克了解了. All rights reserved.
//

#import "TWGridLayout.h"

@interface TWGridLayout ()

@property (nonatomic,strong) NSMutableArray *attrsArray;

@end

@implementation TWGridLayout

-(NSMutableArray *)attrsArray
{
    if (!_attrsArray) {
        _attrsArray = [NSMutableArray array];
    }
    return _attrsArray;
}

-(void)prepareLayout
{
    [super prepareLayout];
    
    [self.attrsArray removeAllObjects];
    
    //NSMutableArray *array = [NSMutableArray array];
    
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    
    for (NSInteger i = 0; i < count; i++) {
        //创建
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
        
        CGFloat width = self.collectionView.frame.size.width *0.5;
        if (i == 0) {
            CGFloat height = width;
            CGFloat x = 0;
            CGFloat y = 0;
            attrs.frame =CGRectMake(x, y, width, height);
        }else if (i == 1){
            CGFloat height = width *0.5;
            CGFloat x = width;
            CGFloat y = 0;
            attrs.frame =CGRectMake(x, y, width, height);
        }else if (i == 2){
            CGFloat height = width *0.5;
            CGFloat x = width;
            CGFloat y = height;
            attrs.frame =CGRectMake(x, y, width, height);
        }else if (i == 3){
            CGFloat height = width *0.5;
            CGFloat x = 0;
            CGFloat y = width;
            attrs.frame =CGRectMake(x, y, width, height);
        }else if (i == 4){
            CGFloat height = width *0.5;
            CGFloat x = 0;
            CGFloat y = height + width;
            attrs.frame =CGRectMake(x, y, width, height);
        }else if (i == 5){
            CGFloat height = width;
            CGFloat x = width;
            CGFloat y = height;
            attrs.frame =CGRectMake(x, y, width, height);
        }else{
            UICollectionViewLayoutAttributes *lastAttrs = self.attrsArray[i -6];
            CGRect lastFrame = lastAttrs.frame;
            lastFrame.origin.y += 2 *width;
            attrs.frame = lastFrame;
        }
        
        [self.attrsArray addObject:attrs];
    }

    
    
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    
    return self.attrsArray;
}

//重写这个方法确定collectionView的大小
- (CGSize)collectionViewContentSize
{

    NSInteger count = [self.collectionView numberOfItemsInSection:0];

    NSInteger rows = ( count + 3 - 1) / 3;
  
    CGFloat rowHeight = self.collectionView.frame.size.width * 0.5;
    
    return CGSizeMake(0, rowHeight * rows);
}

@end
